<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>优先级队列</title>
  </head>
  <body>
  </body>
  <script type="text/javascript">
    function PriorityQueue() {
      function QueueElement(element, priority) {
        this.element = element
        this.priority = priority
      }

      // 封装属性
      this.items = []
      
      //1.实现插入
      PriorityQueue.prototype.enqueue = function(element, priority) {
        // 创建QueueElement对象
        let queueElement = new QueueElement(element, priority)

        // 判断是否为空
        if (this.items.length == 0) {
          this.items.push(queueElement)
        } else {
          let add = false
          for (let i = 0; i < this.items.length; i++) {
            if (queueElement.priority < this.items[i].priority) {
              this.items.splice(i, 0, queueElement)
              add = true
              break
            }
          }
           // 遍历完所有的元素, 优先级都大于新插入的元素时, 就插入到最后
          if (!add) {
            this.items.push(queueElement)
          }
        }
      }
      // 2.删除元素的方法
      PriorityQueue.prototype.dequeue = function() {
        return this.items.shift()
      }

      // 3.获取前端的元素
      PriorityQueue.prototype.front = function() {
        return this.items[0]
      }

      // 4.查看元素是否为空
      PriorityQueue.prototype.isEmpty = function() {
        return this.items.length == 0
      }

      // 5.获取元素的个数
     PriorityQueue.prototype.size = function() {
        return this.items.length
      }
      // 6.toString方法
      PriorityQueue.prototype.toString= function() {
         var resultString = ''
         for (let i = 0; i < this.items.length; i++) {
             resultString = this.items[i] + ''
         }
         return resultString
       }
    }
    
    
    // 测试代码
    // 创建优先级队列对象
    let pQueue = new PriorityQueue()
    
    // 添加元素
    pQueue.enqueue("abc", 10)
    pQueue.enqueue("cba", 5)
    pQueue.enqueue("nba", 12)
    pQueue.enqueue("mba", 3)
    
    // 遍历所有的元素
    let size = pQueue.size()
    for (let i = 0; i < size; i++) {
        let item = pQueue.dequeue()
        console.log(item.element + "-" + item.priority)
    }
  </script>
</html>
